package ;

import js.node.Http;
import js.node.http.Server;
import js.node.SocketIo.SocketNamespace;
import js.npm.Express;
import js.npm.express.Request;
import js.npm.express.Response;
import js.npm.mongoose.Mongoose;
import js.support.Error;

/**
 * ...
 * @author Grouuu
 */

class AppServer 
{
	private static inline var HOST_BDD:String = "mongodb://localhost/BMP/"; // local
	//private static inline var HOST_BDD:String = "mongodb://92.243.10.100"; // external
	private static inline var PORT:Int = 8080; // TODO : mettre 80 en prod
	
	private static var instance:AppServer;
	
	private var db:Mongoose;
	private var app:Express;
	private var server:Server;
	//private var manager:BDDManager;
	//private var socket:SocketIoManager;
	//private var listSockets:Array<SocketNamespace>;
	
	// http://dailyjs.com/2010/11/22/node-tutorial-4/
	
	public static function main():Void
	{
		instance = new AppServer();
	}
	
	public function new():Void
	{
		//listSockets = new Array<SocketNamespace>();
		
		initBDD();
		initApp();
		initHTTP();
		initSocket();
		
		//manager = new BDDManager();
	}
	
	// INIT ///////////////////////////////////////////////////////////////////////////////////////
	
	private function initBDD():Void
	{
		db = js.npm.Mongoose._.connect(HOST_BDD, cast cb_connect);
	}
	
	private function initApp():Void
	{
		app = new Express();
		
		app.get("*", cb_handle);
	}
	
	private function initHTTP():Void
	{
		server = Http.createServer(app);
		
		server.listen(PORT);
	}
	
	private function initSocket():Void
	{
		socket = Node.require("socket.io").listen(server).set("log level", 2);
		
		socket.sockets.on("connection", cb_socketConnection);
	}
	
	// SOCKET /////////////////////////////////////////////////////////////////////////////////////
	
	private function cb_socketConnection(socket:SocketNamespace):Void
	{
		trace("new socket");
		
		listSockets.push(socket);
	}
	
	// APP ////////////////////////////////////////////////////////////////////////////////////////
	
	private function cb_handle(req:Request, res:Response):Void
	{
		res.render("|¯¯¯¯|\¯¯¯\|¯¯¯¯\__/¯¯¯¯||¯¯¯¯|\¯¯¯\\n|    |/   /|            ||    | |   |\n|    |\   \|   |\__/|   ||    |/   /\n|____|/___/|___|    |___||____|¯¯¯");
	}
	
	// BDD ////////////////////////////////////////////////////////////////////////////////////////
	
	private function cb_connect(err:Error):Void
	{
		if (err == null)
		{
			trace("[AppServer]::start >> connection réussie avec la base de données");
		}
		else
		{
			trace("ERROR [AppServer]::start >> erreur lors de la connection à la base de données : " + err);
		}
	}
}